package com.xj.ideatest.utils;

import com.mysql.cj.jdbc.MysqlDataSource;
import com.xj.ideatest.dao.XmxxMapper;
import com.xj.ideatest.model.XmglXtXmxx;
import org.apache.ibatis.builder.xml.XMLConfigBuilder;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        System.out.println("MybatisUtil开始加载");
        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:3306/JKGL");
        dataSource.setUser("root");
        dataSource.setPassword("root");
        InputStream resourceAsStream = MybatisUtil.class.getResourceAsStream("/MapperConfiguration.xml");


        XMLConfigBuilder parser = new XMLConfigBuilder(resourceAsStream);
        Configuration config = parser.parse();

        Environment.Builder builder = new Environment.Builder("default");
        builder.transactionFactory(new JdbcTransactionFactory());
        builder.dataSource(dataSource);
        config.setEnvironment(builder.build());
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(config);
        System.out.println("MybatisUtil成功加载");
    }

    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }

    public static <T> T getMapper(Class<T> tClass) {
        return getSqlSession().getConfiguration().getMapper(tClass, getSqlSession());
    }

    public static void main(String[] args) {
        XmxxMapper xmxxMapper = MybatisUtil.getMapper(XmxxMapper.class);
        XmglXtXmxx xmglXtXmxx = new XmglXtXmxx();
        List<XmglXtXmxx> xmglXtXmxxes = xmxxMapper.queryXmlb(xmglXtXmxx);
        System.out.println(xmglXtXmxxes);
    }
}
